package it.wyx.kafkaclients.consumer.offset;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.common.serialization.StringDeserializer;

/**
 * 手动提交-同步提交
 * @author wyx
 * @version V 1
 * @Date 2022/10/30
 */
public class CustomConsumerByHandSync {
	private static final String BROKER_LIST = "localhost:9092";
	private static final String TOPIC = "test-topic";
	private static final String GROUP_ID = "test-group";

	public static void main(String[] args) {
		Properties properties = new Properties();
		properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, BROKER_LIST);
		properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
		properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
		properties.put(ConsumerConfig.GROUP_ID_CONFIG, GROUP_ID);
		// 是否自动提交offset
		properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);

		KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);

		consumer.subscribe(Collections.singletonList(TOPIC));

		while (true) {
			ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
			System.out.println("接收消费records");
			for (ConsumerRecord<String, String> record : records) {
				System.out.println(record);
			}
			// 同步提交offset
			consumer.commitSync();
		}
	}
}
